<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\Log;
use App\Helper\Util;
use Hyperf\DbConnection\Db;
use App\Helper\Calendar;

/**
 * 演出服务
 */
class ShowService 
{
    /**
     * [__construct description] 构造函数
     */
    public function __construct()
    {}
    /**
     * 获取演出-整月
     * [getShowMonth description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getShowMonth($params)
    {
        $person_id = $params['person_id'];
        $month = $params['month'];
        $city_id = $params['city_id'];
        $sort = $params['sort'];
        $where = [['is_del', '=', 0],['status', '=', 1]];
        if(!empty($person_id)){
            $where[] = ['person_id', '=', $person_id];
        }
        if(!empty($city_id)){
            $where[] = ['city_id', '=', $city_id];
        }
        if(empty($sort)){
            $sort = "grabdate";
        }
        if($sort=="grabdate"){
            if(!empty($month)){
                $where[] = [Db::raw('FROM_UNIXTIME(grabdate,"%Y-%m")'), '=', $month];
            }
        }elseif($sort=="actdate"){
            if(!empty($month)){
                $where[] = [Db::raw('FROM_UNIXTIME(actdate,"%Y-%m")'), '=', $month];
            }
        }
        $columns = [
            'id',
            'show_id',
            'city_id',
            'place_id',
            'name',
            'is_realname',
            'platform',
            'level'
        ];
        $datas = Db::table('vote_showdate')
            ->select($columns)
            ->where($where)
            ->orderBy($sort, 'asc')
            ->get()
            ->toArray();
        $return_data = [];
        if(!empty($datas)){
            foreach ($datas as $data) {
                $show_info = Db::table('vote_show')
                    ->select(['name','image'])
                    ->where(['id'=>$data['show_id']])
                    ->first();
                $city_name = Db::table('conf_provinces')
                    ->where(['id'=>$data['city_id']])
                    ->value("name");
                $place_name = Db::table('place')
                    ->where(['id'=>$data['place_id']])
                    ->value("name");
                $return_data[] = [
                    'id'=>$data['id'],
                    'name'=>$data['name'],
                    'show_image'=>$show_info['image'],
                    'city_name'=>$city_name,
                    'place_name'=>$place_name,
                    'level'=>$this->autoPrice($data['level']),
                    'platform'=>$this->platformDetail($data['platform']),
                    'exdate'=>$this->formatShowdateList($data['id'],$params['user_id'])
                ];
            }
        }
        return $return_data;
    }
    /**
     * 演出详情
     * [getShowDetail description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getShowDetail($params)
    {
        $showdate_id = $params['showdate_id'];
        $where = [['is_del', '=', 0],['status', '=', 1],['id', '=', $showdate_id]];
        $columns = [
            'id',
            'show_id',
            'city_id',
            'place_id',
            'name',
            'is_realname',
            'platform',
            'level'
        ];
        $data = Db::table('vote_showdate')
            ->select($columns)
            ->where($where)
            ->first();
        $return_data = [];
        if(!empty($data)){
            $show_info = Db::table('vote_show')
                ->select(['name','image'])
                ->where(['id'=>$data['show_id']])
                ->first();
            $city_name = Db::table('conf_provinces')
                ->where(['id'=>$data['city_id']])
                ->value("name");
            $place_name = Db::table('place')
                ->where(['id'=>$data['place_id']])
                ->value("name");
            $return_data = [
                'id'=>$data['id'],
                'name'=>$data['name'],
                'show_image'=>$show_info['image'],
                'city_name'=>$city_name,
                'place_name'=>$place_name,
                'level'=>$this->autoPrice($data['level']),
                'platform'=>$this->platformDetailWithId($data['platform']),
                'exdate'=>$this->formatShowdateList($data['id'],$params['user_id'])
            ];
        }
        return $return_data;
    }
    /**
     * 列表页具体时间
     * [formatShowdateList description]
     * @param  [type] $showdate_id [description]
     * @param  [type] $user_id     [description]
     * @return [type]              [description]
     */
    public function formatShowdateList($showdate_id,$user_id)
    {
        $exdate = $this->getShowdateDetail($showdate_id);
        $return_data = [];
        if(!empty($exdate)){
            foreach ($exdate as $key => $value) {
                $remind_time = Db::table('user_sub')
                    ->where(['std_id'=>$value['id'],'user_id'=>$user_id,'status'=>1,'is_del'=>0])
                    ->value("remind_time");
                $sub_status = 0;
                if(!empty($remind_time)){
                    $sub_status = 1;
                }
                if(!empty($value['grabtime']) && $value['grabtime']<=time()){
                    $sub_status = 2;
                }
                if(empty($value['grabtime'])){
                    $sub_status = 3;
                }
                $return_data[] = [
                    'grabdate_id' => $value['id'],
                    'show_gbtime' => !empty($value['grabtime'])?date("m月d日 H:i", $value['grabtime']):"未发布，发布后可添加提醒",
                    'show_actime' => date("Y.m.d", $value['begin_date'])."-".date("m.d", $value['end_date']),
                    'sub_status' => $sub_status
                ];
            }
        }
        return $return_data;
    }
    /**
     * 获取订阅详情
     * [getSubDetail description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getSubDetail($params)
    {
        $grabdate_id = $params['grabdate_id'];
        $user_id = $params['user_id'];
        $columns = [
            'id',
            'begin_date',
            'end_date',
            'exdate',
            'acttime',
            'grabtime'
        ];
        $data = Db::table('vote_showdate_detail')
            ->select($columns)
            ->where(['id'=>$grabdate_id,'is_del'=>0,'status'=>1])
            ->first();
        if(empty($data)){
            return NULL;
        }
        $remind_time = Db::table('user_sub')
            ->where(['std_id'=>$grabdate_id,'user_id'=>$user_id,'status'=>1,'is_del'=>0])
            ->value("remind_time");
        $sub_status = 0;
        if(!empty($remind_time)){
            $sub_status = 1;
        }
        if(!empty($data['grabtime']) && $data['grabtime']<=time()){
            $sub_status = 2;
        }
        if(empty($data['grabtime'])){
            $sub_status = 3;
        }
        if($sub_status==2 || $sub_status==3){
            return false;
        }
        $options = $this->getOption($data['grabtime'], $remind_time);
        if($sub_status==0){
            $show_minute = $options['gbt_minute'];
            if(strlen($show_minute)==1){
                $show_minute = "0".$show_minute;
            }
            $remind_time_text = date("n月d日", $data['grabtime'])." ".$options['gbt_hour'].":".$show_minute."我们将以推送\n方式提醒您";
        }elseif($sub_status==1){
            $remind_time_text = "您已设置".date("H:i", $remind_time)."提醒，取消将不会\n收到抢购推送，确定取消？";
        }
        $return_data = [
            'grabdate_id' => $grabdate_id,
            'grabtime' => date("Y-m-d H:i", $data['grabtime']),
            'show_gbtime' => date("m月d日 H:i", $data['grabtime']),
            'show_actime' => date("Y.m.d", $data['begin_date'])."-".date("m.d", $data['end_date'])." ".$data['acttime'],
            'sub_status' => $sub_status,
            'remind_time' => $remind_time,
            'remind_time_text' => $remind_time_text,
            'options' => $options,
        ];

        return $return_data;
    }
    /**
     * 获取订阅设置项
     * [getOption description]
     * @param  [type] $grabtime    [description]
     * @param  [type] $remind_time [description]
     * @return [type]              [description]
     */
    public function getOption($grabtime,$remind_time)
    {
        $gbt_hour = date("G", $grabtime);
        $gbt_minute = date("i", $grabtime);
        $gbt_minute_ori = $gbt_minute;
        $gbt_minute = preg_replace('/^0/', "", $gbt_minute);
        $rmt_hour = !empty($remind_time)?date("G", $remind_time):NULL;
        $rmt_minute = !empty($remind_time)?date("i", $remind_time):NULL;
        $max_hour = (string)$gbt_hour;
        $min_hour = (string)($gbt_hour-1);
        $max_minute = '59';
        $min_minute = "0";
        $max_hour_min_minute = $gbt_minute>0?"0":"0";

        if($gbt_minute<=10){
            $abs = $gbt_minute-10;
            $gbt_minute = (string)(60+$abs);
            $return_data = [
                'gbt_date'=>date("Y-m-d", $grabtime),
                'gbt_hour'=>$min_hour,
                'gbt_minute'=>$gbt_minute,
                'rmt_hour'=>$rmt_hour,
                'rmt_minute'=>$rmt_minute,
                'max_hour'=>$min_hour,
                'min_hour'=>$min_hour,
                'minute'=>[
                    $min_hour=>[
                        'max_minute'=>"59",
                        'min_minute'=>"0"
                    ],
                    $min_hour=>[
                        'max_minute'=>"59",
                        'min_minute'=>"0"
                    ]
                ]
            ];
        }else{
            $gbt_minute = (string)($gbt_minute-10);
            $return_data = [
                'gbt_date'=>date("Y-m-d", $grabtime),
                'gbt_hour'=>$gbt_hour,
                'gbt_minute'=>$gbt_minute,
                'rmt_hour'=>$rmt_hour,
                'rmt_minute'=>$rmt_minute,
                'max_hour'=>$max_hour,
                'min_hour'=>$min_hour,
                'minute'=>[
                    $max_hour=>[
                        'max_minute'=>$gbt_minute,
                        'min_minute'=>$max_hour_min_minute
                    ],
                    $min_hour=>[
                        'max_minute'=>"59",
                        'min_minute'=>"0"
                    ]
                ]
            ];
        }
        return $return_data;
    }
    /**
     * 获取票档详情
     * [getLevelDetail description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getLevelDetail($params)
    {
        $showdate_id = $params['showdate_id'];
        $user_id = $params['user_id'];
        $level = Db::table('vote_showdate')
            ->where(['id'=>$showdate_id,'is_del'=>0,'status'=>1])
            ->value("level");
        $exdates = Db::table('vote_showdate_detail')
            ->select(['exdate'])
            ->where(['showdate_id'=>$showdate_id,'status'=>1,'is_del'=>0])
            ->get()
            ->toArray();
        $level_array = [];
        if(!empty($level)){
            $level_json = json_decode($level, true);
            foreach ($level_json as $key => $value) {
                $level_array[$value['price']] = $value['price']."元(".$value['name'].")";
            }
            ksort($level_array);
            $level_array = array_values($level_array);
        }
        $exdate_array = [];
        if(!empty($exdates)){
            foreach ($exdates as $key => $value) {
                $exdate = json_decode($value['exdate'], true);
                $dta = $exdate['dta'];
                foreach ($dta as &$dtav) {
                    $week = Calendar::getWeekDay($dtav);
                    $time = date("H:i", strtotime($dtav." ".$exdate['show_time']));
                    $dtav .= " ".$week." ".$time;
                }
                $exdate_array = array_merge($exdate_array,$dta);
            }
        }
        $return_data = [
            'level' => $level_array,
            'exdate' => $exdate_array
        ];

        return $return_data;
    }
    /**
     * 平台信息
     * [platformDetail description]
     * @param  [type] $platform_ids [description]
     * @return [type]               [description]
     */
    public function platformDetail($platform_ids)
    {
        $array = array_filter(explode(",", $platform_ids));
        if(empty($array)){
            return NULL;
        }
        $return_data = [];
        foreach ($array as $key => $value) {
            $platform_info = Db::table('platform')
                ->select(['name','image'])
                ->where(['id'=>$value])
                ->first();
            $return_data[] = $platform_info;
        }
        return $return_data;
    }
    /**
     * 平台信息
     * [platformDetailWithId description]
     * @param  [type] $platform_ids [description]
     * @return [type]               [description]
     */
    public function platformDetailWithId($platform_ids)
    {
        $array = array_filter(explode(",", $platform_ids));
        if(empty($array)){
            return NULL;
        }
        $return_data = [];
        foreach ($array as $key => $value) {
            $platform_info = Db::table('platform')
                ->select(['id','name','image'])
                ->where(['id'=>$value])
                ->first();
            $return_data[] = $platform_info;
        }
        return $return_data;
    }
    /**
     * 自动排序获取价格
     * [autoPrice description]
     * @param  [type] $price_str [description]
     * @return [type]            [description]
     */
    public function autoPrice($price_str)
    {
        $array = json_decode($price_str,true);
        if(empty($array)){
            return NULL;
        }
        $return_data = [];
        foreach ($array as $key => $value) {
            $return_data[] = $value['price'];
        }
        sort($return_data);
        $retrun_str = "￥".$return_data[0]."-".$return_data[count($return_data)-1];
        return $retrun_str;
    }
    /**
     * 演出系列保存
     * [showSave description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function showSave($params)
    {
        if(!empty($params['id'])){
            $save_data = [
                'updated_at'=>time()
            ];
            if(!empty($params['person_id'])){
                $save_data['person_id'] = $params['person_id'];
            }
            if(!empty($params['name'])){
                $save_data['name'] = $params['name'];
            }
            if(!empty($params['image'])){
                $save_data['image'] = $params['image'];
            }
            if(!empty($params['sort'])){
                $save_data['sort'] = $params['sort'];
            }
            if(isset($params['status'])){
                $save_data['status'] = $params['status'];
            }
            Db::table('vote_show')
                ->where(['id'=>$params['id']])
                ->update($save_data);
        }else{
            $save_data = [
                'person_id'=>$params['person_id'],
                'name'=>$params['name'],
                'image'=>$params['image'],
                'sort'=>$params['sort']??0,
                'status'=>$params['status']??0,
                'created_at'=>time()
            ];
            Db::table('vote_show')
                ->insert($save_data);
        }
        return true;
    }
    /**
     * 演出场次保存
     * [showdateSave description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function showdateSave($params)
    {
        if(!empty($params['id'])){
            $save_data = [
                'updated_at'=>time()
            ];
            if(!empty($params['show_id'])){
                $save_data['show_id'] = $params['show_id'];
            }
            if(!empty($params['person_id'])){
                $save_data['person_id'] = $params['person_id'];
            }
            if(!empty($params['province_id'])){
                $save_data['province_id'] = $params['province_id'];
            }
            if(!empty($params['city_id'])){
                $save_data['city_id'] = $params['city_id'];
            }
            if(!empty($params['place_id'])){
                $save_data['place_id'] = $params['place_id'];
            }
            if(!empty($params['name'])){
                $save_data['name'] = $params['name'];
            }
            if(isset($params['is_realname'])){
                $save_data['is_realname'] = $params['is_realname'];
            }
            if(!empty($params['platform'])){
                $save_data['platform'] = ",".$params['platform'].",";
            }
            if(!empty($params['ft_exdate']['actdate'])){
                $save_data['actdate'] = $params['ft_exdate']['actdate'];
            }
            if(!empty($params['ft_exdate']['grabdate'])){
                $save_data['grabdate'] = $params['ft_exdate']['grabdate'];
            }else{
                $save_data['grabdate'] = 0;
            }
            if(!empty($params['level'])){
                $save_data['level'] = $params['level'];
            }
            if(!empty($params['sort'])){
                $save_data['sort'] = $params['sort'];
            }
            if(isset($params['status'])){
                $save_data['status'] = $params['status'];
            }
            Db::table('vote_showdate')
                ->where(['id'=>$params['id']])
                ->update($save_data);
        }else{
            $save_data = [
                'show_id'=>$params['show_id'],
                'person_id'=>$params['person_id'],
                'province_id'=>$params['province_id'],
                'city_id'=>$params['city_id'],
                'place_id'=>$params['place_id'],
                'name'=>$params['name'],
                'is_realname'=>$params['is_realname'],
                'platform'=>",".$params['platform'].",",
                'actdate'=>$params['ft_exdate']['actdate'],
                'grabdate'=>$params['ft_exdate']['grabdate'],
                'level'=>$params['level'],
                'sort'=>$params['sort']??0,
                'status'=>$params['status']??0,
                'created_at'=>time()
            ];
            $res = Db::table('vote_showdate')
                ->insertGetId($save_data);
            $params['id'] = $res;
        }
        $this->synDetail($params);
        return true;
    }
    /**
     * 同步详情表
     * [synDetail description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function synDetail($params)
    {
        $ft_exdate = $params['ft_exdate']['exdate'];
        $handle_data = [];
        foreach ($ft_exdate as $key => $value) {
            $gtime = !empty($value['grab_time'])?strtotime($value['grab_time']):0;
            $begin_date = strtotime($value['begin_date']);
            $handle_key = $begin_date."_".$gtime;
            $handle_data[$handle_key] = $value;
            $exists_id = Db::table('vote_showdate_detail')
                ->where(['showdate_id'=>$params['id'],'grabtime'=>$gtime,'begin_date'=>$begin_date])
                ->value("id");
            if(!empty($exists_id)){
                $save_data = [
                    'begin_date'=>$begin_date,
                    'end_date'=>strtotime($value['end_date']),
                    'exdate'=>json_encode($value, JSON_UNESCAPED_UNICODE),
                    'acttime'=>$value['show_time'],
                    'grabtime'=>$gtime,
                    'is_del'=>0,
                    'updated_at'=>time()
                ];
                Db::table('vote_showdate_detail')
                    ->where(['id'=>$exists_id])
                    ->update($save_data);
            }else{
                $save_data = [
                    'showdate_id'=>$params['id'],
                    'begin_date'=>strtotime($value['begin_date']),
                    'end_date'=>strtotime($value['end_date']),
                    'exdate'=>json_encode($value, JSON_UNESCAPED_UNICODE),
                    'acttime'=>$value['show_time'],
                    'grabtime'=>$gtime,
                    'created_at'=>time()
                ];
                Db::table('vote_showdate_detail')
                    ->insert($save_data);
            }
        }
        $where = [
            ['is_del', '=', 0],
            ['showdate_id', '=', $params['id']],
        ];
        $datas = Db::table('vote_showdate_detail')
            ->select(['id','begin_date','grabtime'])
            ->where($where)
            ->get()
            ->toArray();
        foreach ($datas as $key => $value) {
            $vk = $value['begin_date']."_".$value['grabtime'];
            if(!array_key_exists($vk, $handle_data)){
                Db::table('vote_showdate_detail')
                    ->where(['id'=>$value['id']])
                    ->update(['is_del'=>1]);
                // $this->synDelSubByStdId($value['id']);
            }
        }
    }
    /**
     * 根据具体时间ID删除订阅
     * [synDelSub description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function synDelSubByStdId($std_id)
    {
        Db::table('user_sub')
            ->where(['std_id'=>$std_id])
            ->update(['is_del'=>1]);
    }
    /**
     * 根据场次ID删除订阅
     * [synDelSubBySdId description]
     * @param  [type] $sd_id [description]
     * @return [type]        [description]
     */
    public function synDelSubBySdId($sd_id)
    {
        $datas = Db::table('vote_showdate_detail')
            ->select(['id'])
            ->where(['showdate_id'=>$sd_id])
            ->get()
            ->toArray();
        foreach ($datas as $key => $value) {
            Db::table('user_sub')
                ->where(['std_id'=>$value['id']])
                ->update(['is_del'=>1]);
        }
    }
    /**
     * 格式化时间
     * [formatExdate description]
     * @param  [type] $exdate [description]
     * @return [type]         [description]
     */
    public function formatExdate($exdate)
    {
        $actdate = 0;
        $grabdate = 0;
        $exdate_array = json_decode($exdate, true);
        foreach ($exdate_array as &$ed) {
            if(!empty($ed['act_time'])){
                $ed['dta'] = $ed['act_time'];
                $ed['begin_date'] = $ed['act_time'][0];
                $ed['end_date'] = $ed['act_time'][count($ed['act_time'])-1];
            }else{
                $ed['dta'] = Calendar::getCalByBeginAndEnd($ed['begin_date'],$ed['end_date']);
            }
            $ed['begin_datetime'] = $ed['begin_date']." ".$ed['show_time'];
            $begin_date_time = strtotime($ed['begin_datetime']);
            $grab_date_time = strtotime($ed['grab_time']);
            if(empty($actdate)){
                $actdate = $begin_date_time;
            }else{
                if($begin_date_time<$actdate){
                    $actdate = $begin_date_time;
                }
            }
            if(empty($grabdate)){
                $grabdate = $grab_date_time;
            }else{
                if($grab_date_time<$grabdate){
                    $grabdate = $grab_date_time;
                }
            }
        }
        $return_data = [
            'actdate'=>$actdate,
            'grabdate'=>$grabdate,
            'exdate'=>$exdate_array
        ];
        return $return_data;
    }
    /**
     * 获取场次时间详情
     * [getShowdateDetail description]
     * @param  [type] $showdate_id [description]
     * @return [type]              [description]
     */
    public function getShowdateDetail($showdate_id)
    {
        $columns = [
            'id',
            'begin_date',
            'end_date',
            'exdate',
            'acttime',
            'grabtime'
        ];
        $data = Db::table('vote_showdate_detail')
            ->select($columns)
            ->where(['showdate_id'=>$showdate_id,'is_del'=>0,'status'=>1])
            ->orderBy('begin_date', 'asc')
            ->get()
            ->toArray();
        if(!empty($data)){
            foreach ($data as $key => &$value) {
                $value['exdate'] = json_decode($value['exdate'],true);
            }
        }
        return $data;
    }
}
